<template>
  <div class="app-main-container">
    <div class="app-main-title">{{ $t("message.hyfpkj") }}</div>
    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="auto"
      style="width: 600px"
      label-suffix="："
    >
      <div class="property-title">{{ $t("message.kpxx") }}</div>
      <el-form-item :label="$t('message.hykh')" prop="cardNum">
        <el-input
          v-model="param.cardNum"
          :placeholder="$t('message.qsr') + $t('message.hy1')"
          @keyup.enter.native="searchAction"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="searchAction"
          />
        </el-input>
        <div v-if="showMessage">
          <div class="card-message">
            <div class="first-line">
              <span class="message-title-style">NO.</span>
              <span class="message-value-style">{{ cardMessage.number }}</span>
              <span class="message-value-style">{{
                cardMessage.nickName
              }}</span>
              <span v-if="cardMessage.cardName" class="card-name-style">{{
                cardMessage.cardName
              }}</span>
              <button class="message-title-style close-style" @click="closeOut">
                x
              </button>
            </div>
            <div class="first-line">
              <span class="message-title-style">{{ $t("message.sj") }}：</span>
              <span class="message-value-style">{{ cardMessage.phone }}</span>
              <span class="message-title-style"
                >{{ $t("message.czje") }}：</span
              >
              <span class="message-value-style">{{
                cardMessage.remainingMoney ? cardMessage.remainingMoney : 0
              }}</span>
              <span class="message-title-style"
                >{{ $t("message.zsje") }}：</span
              >
              <span class="message-value-style">{{
                cardMessage.remainingGiveMoney
                  ? cardMessage.remainingGiveMoney
                  : 0
              }}</span>
              <!-- <span class="message-title-style">{{ $t('message.ye') }}：</span>
              <span class="message-value-style">{{ cardMessage.money }}</span> -->
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="$t('message.ttname')" prop="company_title">
        <div style="display: flex">
          <el-select
            v-model="param.id"
            style="width: 500px"
            filterable
            :placeholder="$t('message.qxz') + $t('message.ttname')"
            @change="selectChange"
          >
            <el-option
              v-for="item in titleList"
              :key="item.id"
              :label="item.company_title"
              :value="item.id"
            />
          </el-select>
          <el-button icon="el-icon-plus" @click="addInvoiceTitle" />
        </div>
      </el-form-item>
      <el-form-item :label="$t('message.ttlx')" prop="company_title">
        <el-input
          v-model="param.company_title"
          disabled
          :placeholder="$t('message.gjttxxzddr')"
        />
      </el-form-item>
      <el-form-item
        v-if="param.company_tax"
        :label="$t('message.gssh')"
        prop="company_tax"
      >
        <el-input
          v-model="param.company_tax"
          disabled
          :placeholder="$t('message.gjgjzddr')"
        />
      </el-form-item>
      <el-form-item :label="$t('message.dzyx')" prop="email">
        <el-input v-model="param.email" :placeholder="$t('message.yyjsdzfp')" />
      </el-form-item>
    </el-form>
    <div class="property-title">{{ $t("message.ddxq") }}</div>
    <div class="doumee-filter">
      <el-input
        v-model="filters.orderId"
        clearable
        :placeholder="$t('message.qsr') + $t('message.ddbh')"
      />
      <el-select
        v-model="filters.orderType"
        :placeholder="$t('message.qxz') + $t('message.ddlx')"
      >
        <el-option
          v-for="item in orderTypeList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="filters.payMethod"
        :placeholder="$t('message.qxz') + $t('message.zffs')"
        clearable
      >
        <el-option
          v-for="item in payTypes"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model="filters.stratAmot"
        clearable
        :placeholder="$t('message.qsr') + $t('message.ddzxje')"
      />
      <div class="date-division-line">~</div>
      <el-input
        v-model="filters.endAmot"
        clearable
        :placeholder="$t('message.qsr') + $t('message.ddzdje')"
      />
      <el-button v-preventReClick type="primary" @click="getList(1)">{{
        $t("message.cz")
      }}</el-button>
      <!-- <el-button v-preventReClick @click="clearList">{{ $t('message.clear') }}</el-button> -->
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        align="center"
        :label="$t('message.ddh')"
        min-width="250"
        prop="id"
      />
      <el-table-column
        align="center"
        :label="$t('message.ddxq')"
        prop="orderInfo"
        min-width="300"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.kkpje')"
        min-width="120"
        show-overflow-tooltip
        prop="invoiceMoney"
      />
      <el-table-column
        align="center"
        :label="$t('message.ddje')"
        prop="price"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.ddlx')"
        prop="orderType"
        min-width="140"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.ddly')"
        prop="source"
        min-width="140"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.zffs')"
        prop="payMethod"
        min-width="120"
        show-overflow-tooltip
      />
    </el-table>
    <div class="flex-cc doumee-pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page.sync="pagination.page"
        hide-on-single-page
        @current-change="getList"
      />
    </div>
    <div style="text-align: center">
      <el-button type="primary" :loading="subLoading" @click="confirmBtn">{{
        $t("message.tj")
      }}</el-button>
    </div>
    <el-dialog
      :title="$t('message.add') + $t('message.fptt')"
      :visible.sync="showAddInvoiceTitle"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
    >
      <el-form
        ref="invoiceForm"
        :model="form"
        label-width="auto"
        :rules="addrules"
      >
        <el-form-item :label="$t('message.ttlx')" prop="type">
          <el-radio v-model="form.type" label="0">{{
            $t("message.qydw")
          }}</el-radio>
          <el-radio v-model="form.type" label="1">{{
            $t("message.grfqydw")
          }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('message.ttname')" prop="company_title">
          <el-input
            v-model="form.company_title"
            :placeholder="$t('message.qsr') + $t('message.ttname')"
          />
        </el-form-item>
        <el-form-item
          v-if="form.type == '0'"
          :label="$t('message.gssh')"
          prop="company_tax"
        >
          <el-input
            v-model="form.company_tax"
            :placeholder="$t('message.qsr') + $t('message.gssh')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sfmr')" prop="is_default">
          <el-radio v-model="form.is_default" label="0">{{
            $t("message.fou")
          }}</el-radio>
          <el-radio v-model="form.is_default" label="1">{{
            $t("message.shi")
          }}</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAddInvoiceTitle">{{
          $t("message.qx")
        }}</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="confirmAddInvoiceTitle"
          >{{ $t("message.qr") }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/index";
import store from "@/store";
import {
  configList,
  orderTypeList,
  VIPInfo,
  addInvoiceTitle,
  makeInvoice,
  myInvoiceTitle,
  orderInvoiceListPC,
} from "@/api";

export default {
  name: "InvoiceMember",
  data() {
    return {
      modalDialog: store.getters.dialog,
      subLoading: false,
      meta: [],
      list: [],
      pagination: {
        page: 1,
        rows: 10,
      },
      total: 0,
      orderTypeList: [],
      form: {},
      filters: {},
      param: {},
      listLoading: false,
      showMessage: false,
      showAddInvoiceTitle: false,
      cardMessage: {},
      payTypes: [],
      titleList: [],
      multipleSelection: [],
      rules: {
        cardNum: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.hy2"),
            trigger: "blur",
          },
        ],
        company_title: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.ttlx"),
            trigger: "blur",
          },
        ],
        company_tax: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.gssh"),
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.jsyx"),
            trigger: "blur",
          },
          {
            pattern: /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/,
            message: this.$t("message.qsrzrdyx"),
            trigger: "blur",
          },
        ],
      },
      addrules: {
        type: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.ttlx"),
            trigger: "blur",
          },
        ],
        company_title: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.ttname"),
            trigger: "blur",
          },
        ],
        company_tax: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.gssh"),
            trigger: "blur",
          },
        ],
        is_default: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.sfmr"),
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.meta = this.$route.meta.buttons || [];
    this.payTypesList();
    this.getOrderTypeList();
  },
  methods: {
    payTypesList() {
      configList({ param: { type: "2", code: "1" } })
        .then((res) => {
          if (res.errorCode !== "000000") return;
          this.payTypes = res.recordList;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取订单类型列表
    getOrderTypeList() {
      orderTypeList({
        param: {
          type: "ORDER_TYPE_INVOICE_OPEN",
        },
      }).then((res) => {
        if (res.errorCode !== "000000") return;
        this.orderTypeList = res.recordList;
        this.$set(this.filters, "orderType", this.orderTypeList[0].id);
      });
    },
    getMyInvoiceTitle() {
      if (!this.cardMessage.id) {
        this.$message.warning(this.$t("message.hy5"));
        return;
      }
      myInvoiceTitle({
        param: {
          memberId: this.cardMessage.id,
        },
      })
        .then((res) => {
          if (res.errorCode === "000000") {
            this.titleList = res.recordList;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    searchAction() {
      if (!this.param.cardNum.length) {
        this.$message.error(this.$t("message.qsr") + this.$t("message.hy1"));
        return;
      }
      VIPInfo({
        param: {
          phoneOrNo: this.param.cardNum,
        },
      })
        .then((res) => {
          if (res.errorCode === "000000") {
            this.cardMessage = res.record;
            this.showMessage = true;
            this.getMyInvoiceTitle();
            this.getList(1);
          }
        })
        .catch((err) => {
          console.log(err);
          this.cardMessage = {};
          this.showMessage = false;
        });
    },
    closeOut() {
      this.showMessage = false;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(11, val);
    },
    confirmBtn() {
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$message.error(this.$t("message.qxzykjfpddd"));
        return false;
      }
      const multipleSelection = this.multipleSelection;
      const ids = [];
      multipleSelection.forEach((e) => {
        ids.push(e.id);
      });
      const param = { ...this.param };
      param.titleId = param.id;
      param.ids = ids;
      param.type = !param.company_tax ? "1" : "0";
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.subLoading = true;
          makeInvoice({
            param,
          })
            .then((res) => {
              this.subLoading = false;
              if (res.errorCode === "000000") {
                this.ruleForm = {};
                this.$message.success(this.$t("message.fpkjcg"));
                this.$router.replace({
                  name: "InvoiceList",
                  query: { renovate: 1 },
                });
              }
            })
            .catch((err) => {
              this.subLoading = false;
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    clearList() {
      this.filters = {};
      this.getList(1);
    },
    getList(page) {
      this.listLoading = false;
      const { filters, pagination } = this;
      const venueId = sessionStorage.getItem("venueId");
      if (page) {
        pagination.page = page;
        this.pagination.page = page;
      }
      filters.memberId = this.cardMessage.id;
      pagination.firstQueryTime = parseTime(new Date());
      orderInvoiceListPC({
        pagination,
        param: {
          venueId,
          ...filters,
        },
      })
        .then((res) => {
          this.listLoading = false;
          if (res.errorCode !== "000000") return;
          this.list = res.recordList;
          this.total = res.totalCount;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    selectChange() {
      // const { param } = this.param
      const invoiceitem = this.titleList.find(
        (item) => item.id === this.param.id
      );
      if (invoiceitem) {
        this.param.id = invoiceitem.id;
        this.param.company_title = invoiceitem.company_title;
        this.param.company_tax = invoiceitem.company_tax;
      }
      // for (const invoiceTitle of this.titleList) {
      //   if (invoiceTitle.id === this.param.id) {
      //     const item = JSON.stringify(invoiceTitle)
      //     const invoiceitem = JSON.parse(item)
      //     // this.param = invoiceitem
      //     this.param.id = invoiceitem.id
      //     this.param.company_title = invoiceitem.company_title
      //     this.param.company_tax = invoiceitem.company_tax
      //   }
      // }
    },
    addInvoiceTitle() {
      if (!this.cardMessage.id) {
        this.$message.error(this.$t("message.hy5"));
        return;
      }
      this.form = {};
      this.showAddInvoiceTitle = true;
    },
    confirmAddInvoiceTitle() {
      if (!this.cardMessage.id) {
        this.$message.error(this.$t("message.hy5"));
        return;
      }
      this.form.memberId = this.cardMessage.id;
      this.$refs.invoiceForm.validate((valid) => {
        if (valid) {
          const param = { ...this.form };
          // this.titleList.push(addform)
          addInvoiceTitle({
            param,
          })
            .then((res) => {
              if (res.errorCode === "000000") {
                this.showAddInvoiceTitle = false;
                this.getMyInvoiceTitle();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cancleAddInvoiceTitle() {
      this.showAddInvoiceTitle = false;
      this.form = {};
    },
  },
};
</script>
<style lang="scss" scoped>
.card-message {
  margin-top: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
</style>
